package com.da.javatest.interview.other.print;

/**
 * @author chenlida
 * @date 2020/7/24 14:15
 * @description 两个线程交替打印奇偶
 */
public class PrintOddEven1 {
    private static final Object lock = new Object();
    private static volatile int number = 1;

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            while (true) {
                synchronized (lock) {
                    if (number > 20) {
                        lock.notifyAll();
                        return;
                    }
                    if (number % 2 == 0) {
                        continue;
                    }
                    System.out.println(Thread.currentThread().getName() + number);
                    number++;
                    try {
                        lock.notifyAll();
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t1.setName("oddThread-");
        t1.start();

        Thread t2 = new Thread(() -> {
            while (true) {
                synchronized (lock) {
                    if (number > 20) {
                        lock.notifyAll();
                        return;
                    }
                    if (number % 2 != 0) {
                        continue;
                    }
                    System.out.println(Thread.currentThread().getName() + number);
                    number++;
                    try {
                        lock.notifyAll();
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t2.setName("evenThread-");
        t2.start();
    }
}
